<!--
 * @Author: lmh
 * @Date: 2021-08-06 21:23:06
 * @LastEditTime: 2021-08-08 20:05:09
 * @LastEditors: lmh
 * @Description: vue-数据驱动1
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root">
        <p>{{ name }}</p>
        <p>{{ message }}</p>
        <div>
            <p>{{ name }}-{{ message }}</p>
        </div>
    </div>
</body>
</html>
<script>
    let rkuohao = /\{\{(.+?)\}\}/g; // 匹配花括号内部的东西
    let tmpNode = document.querySelector('#root')
    let data = {
        name: '张三',
        message: '是个法外狂徒'
    }

    function compiler(template, data) {
        for(let i = 0,len = template.childNodes.length; i < len; i++) {
            if (template.childNodes[i].nodeType == 3) {
                let txt = template.childNodes[i].nodeValue
                txt = txt.replace(rkuohao, function(_, g) {
                    return data[g.trim()];
                })
                template.childNodes[i].nodeValue = txt
            }else if (template.childNodes[i].nodeType == 1) {
                compiler(template.childNodes[i], data)
            }
        }
    }

    let generateNode = tmpNode.cloneNode(true) // 加true克隆所有后代
    console.log('原node', tmpNode)
    compiler(generateNode, data)
    console.log('生成后的node', generateNode)
    // tmpNode.parent()
    root.parentNode.replaceChild(generateNode, root)
</script>
